<template>
  <div class='mobile-picVote-wrapper'>
    <!-- 【注】 valid-tip-box 类名将作为paper页面的DOM索引，不能修改 -->
    <div class='valid-tip-box'
         v-if='question.validType === "required"'>
      请<span v-show='question.isMulti'>至少</span>给一个选项投票
    </div>
    <!-- 单选 -->
    <ul class='picVote-list' v-if='!question.isMulti'>
      <li class='option-item'
          v-for='(option, index) of question.optionList'
          :key='index'
          :class='{ active: option.isSelected }'
          @click='selectOption(option)'>
        <div class='item-img' :style='{backgroundImage: `url(${option.imgUrl})`}'>
          <div class='item-result' :class='{show:showResult}'>
            <div class='result-percent'>{{option.votePercentage}}%</div>
            <div class='result-count'>{{option.voteCount}}票</div>
            <div class='result-slider'>
              <div class='slider-line' :style='{maxWidth: `${option.votePercentage}%`}'></div>
            </div>
          </div>
        </div>
        <div class='item-img-preview survey-tool-sprite-bg' @click.stop='previewPic(index)'></div>
        <div class='item-desc survey-tool-sprite-bg'
             v-show='option.description'
             @click.stop='showDesc(option)'>
          ...
        </div>
        <div class='item-content'>
          <div class='option-circle'></div>
          <div class='option-content' v-html='option.title'></div>
        </div>
      </li>
    </ul>
    <!-- 多选 -->
    <ul class='picVote-list' v-if='question.isMulti'>
      <li class='option-item'
          v-for='(option, index) of question.optionList'
          :key='index'
          :class='{ active: option.isSelected }'
          @click='toggleOption(option)'>
        <div class='item-img' :style='{backgroundImage: `url(${option.imgUrl})`}'>
          <div class='item-result' :class='{show:showResult}'>
            <div class='result-percent'>{{option.votePercentage}}%</div>
            <div class='result-count'>{{option.voteCount}}票</div>
            <div class='result-slider'>
              <div class='slider-line' :style='{maxWidth: `${option.votePercentage}%`}'></div>
            </div>
          </div>
        </div>
        <div class='item-img-preview survey-tool-sprite-bg' @click.stop='previewPic(index)'></div>
        <div class='item-desc survey-tool-sprite-bg'
             v-show='option.description'
             @click.stop='showDesc(option)'>
          ...
        </div>
        <div class='item-content'>
          <div class='option-square'></div>
          <div class='option-content' v-html='option.title'></div>
        </div>
      </li>
    </ul>
    <!-- 图片预览 -->
    <div class='pic-preview-wrapper'
         v-if='isPreviewPic'
         @touchmove.stop='forbitScroll'>
      <div class='preview-close iconfont' @click='closePreview'>&#xe623;</div>
      <swiper :options="swiperOption">
        <swiper-slide v-for='(option, index) of question.optionList' :key='"pic" + index'>
          <div class='pic-item'
               :style='{backgroundImage: `url(${option.imgUrl})`}'>
          </div>
        </swiper-slide>
      </swiper>
      <div class='preview-pagination'>
        （{{currPicIndex}}/{{question.optionList.length}}）{{currPicTitle}}
      </div>
    </div>
    <!-- 查看图片描述 -->
    <div class='pic-desc-wrapper'
         v-if='isShowingDesc'
         @touchmove.stop='forbitScroll'>
      <div class='desc-content'>
        <div class='desc-header'>
          <div class='desc-close iconfont' @click='hideDesc'>&#xe623;</div>
        </div>
        <div class='desc-body'>
          <div class='desc-title'>{{currVoteTitle}}</div>
          <div class='desc-box' v-html='currVoteDesc'></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'
export default {
  name: 'mobilepicVote',
  data () {
    let that = this
    return {
      swiperOption: {
        // 设定初始化时slide的索引
        initialSlide: 0,
        // Slides的滑动方向，可设置水平(horizontal)或垂直(vertical)
        direction: 'horizontal',
        // 环状轮播
        loop: false,
        slidesPerView: 'auto',
        loopedSlides: 3,
        loopAdditionalSlides: 0,
        // 滑动之后回调函数
        on: {
          slideChangeTransitionStart: function () {
            that.currPicIndex = this.realIndex + 1
            that.currPicTitle = that.formatDetail(that.question.optionList[this.realIndex].title)
          }
        }
      },
      isPreviewPic: false,
      currPicIndex: 1,
      currPicTitle: '',
      currVoteTitle: '',
      currVoteDesc: '',
      isShowingDesc: false,
      showResult: false
    }
  },
  components: {
    swiper,
    swiperSlide
  },
  props: {
    question: {
      type: Object,
      default () {
        return {}
      }
    },
    isRecord: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    forbitScroll (e) {
      e.preventDefault()
    },
    resetValidType () {
      this.question.validType = ''
    },
    // 单选
    selectOption (opt) {
      if (this.isRecord) {
        return false
      }
      this.resetValidType()
      this.question.optionList.forEach(option => {
        if (option.optionId === opt.optionId) {
          option.isSelected = true
        } else {
          option.isSelected = false
        }
      })
      let extendAttr = JSON.parse(this.question.extendAttr || '{}')
      if (extendAttr.showVoteResult) {
        this.showResult = true
        this.updateVoteResult()
      }
    },
    // 多选
    toggleOption (opt) {
      if (this.isRecord) {
        return false
      }
      this.resetValidType()
      // 如果是选中该选项，需要判断最大选择个数
      if (this.question.selectLimit) {
        if (!opt.isSelected) {
          let selectedOptions = this.question.optionList.filter(opt => opt.isSelected)
          if (selectedOptions.length >= this.question.selectLimit) {
            return false
          }
        }
      }
      opt.isSelected = !opt.isSelected
      let extendAttr = JSON.parse(this.question.extendAttr || '{}')
      if (extendAttr.showVoteResult) {
        this.showResult = true
        this.updateVoteResult()
      }
    },
    closePreview () {
      this.isPreviewPic = false
    },
    previewPic (index) {
      this.swiperOption.initialSlide = index
      if (index === 0) {
        this.currPicIndex = 1
        this.currPicTitle = this.formatDetail(this.question.optionList[0].title)
      }
      this.isPreviewPic = true
    },
    showDesc (option) {
      this.currVoteTitle = this.formatDetail(option.title)
      this.currVoteDesc = option.description
      this.isShowingDesc = true
    },
    formatDetail (description) {
      return description.replace(/<.*?>/g, '').slice(0, 30)
    },
    hideDesc () {
      this.isShowingDesc = false
    },
    // 根据当前用户投票的选项，获取最新投票结果，并更新数据
    updateVoteResult () {
      this.$_load.show()
      // 线上
      let url = `${this.SERVICE_UPGRADE_SURVEY}/${this.question.surveyId}/vote`
      let param = {
        questionId: this.question.questionId
      }
      this.$post(url, param).then(res => {
        this.$_load.hide()
        if (res.code === 200 && res.data) {
          let voteResult = res.data
          this.question.optionList.forEach(option => {
            let targetOption = voteResult.optionStat.filter(opt => opt.optionId === option.optionId)[0]
            if (targetOption) {
              let voteCount = targetOption.voteCount
              // 如果是答题模式，需要加上自己的选择
              if (!this.isRecord) {
                option.voteCount = option.isSelected ? voteCount + 1 : voteCount
                option.votePercentage = parseInt(option.voteCount / (voteResult.voteCount + 1) * 10000) / 100
              } else {
                option.voteCount = voteCount
                option.votePercentage = parseInt(option.voteCount / voteResult.voteCount * 10000) / 100
              }
            } else {
              option.voteCount = option.isSelected ? 1 : 0
              // option.votePercentage = option.isSelected ? 100 : 0
              option.votePercentage = parseInt(option.voteCount / (voteResult.voteCount + 1) * 10000) / 100
            }
          })
          console.log('optionList: ', this.question.optionList)
        }
      }).catch(e => {
        this.$_load.hide()
      })
    },
    init () {
      // 如果是查看记录模式, 回显答题记录
      if (this.isRecord) {
        if (this.question.answer) {
          // let optionResults = this.question.answer.optionResults
          let optionResults = this.question.answer
          this.question.optionList.forEach(option => {
            let targetOption = optionResults.filter(item => item.optionId === option.optionId)[0]
            if (targetOption) {
              option.isSelected = true
            } else {
              option.isSelected = false
            }
          })
        }
        let extendAttr = JSON.parse(this.question.extendAttr || '{}')
        if (extendAttr.showVoteResult) {
          this.showResult = true
          this.updateVoteResult()
        }
      }
    }
  },
  created () {
    this.init()
    console.log('question: ', this.question)
  }
}
</script>

<style lang="stylus" scoped>
.mobile-picVote-wrapper
  margin-top 10px
  .valid-tip-box
    color #ef6262
    font-size 14px
    margin-bottom 5px
  .picVote-list
    display flex
    flex-wrap wrap
    align-items flex-start
    .option-item
      width calc((100% - 12px)*0.5)
      margin-right 12px
      margin-bottom 12px
      border 1px solid #dde5ed
      border-radius 4px
      display flex
      flex-direction column
      box-sizing border-box
      overflow hidden
      transform rotate(0)
      cursor pointer
      &:nth-of-type(2n)
        margin-right 0
      &.active
        background rgba(38, 114, 255, 0.1)
        border-color #2672ff
        .item-content
          .option-circle
            position relative
            border-color #2672ff
            &::after
              content ''
              position absolute
              left 0
              right 0
              top 0
              bottom 0
              margin auto
              display block
              width 10px
              height 10px
              background #2672ff
              border-radius 50%
          .option-square
            position relative
            border-color #2672ff
            &::after
              content: "";
              display: inline-block;
              width: 7px;
              height: 13px;
              border-right-style: solid;
              border-bottom-style: solid;
              border-right-width: 3px;
              border-bottom-width: 3px;
              border-color #2672ff
              transform: rotate(45deg) scale(0.7) translate3d(-2px, -5px, 0);
      .item-img
        position relative
        display block
        width 100%
        padding-bottom 100%
        bgCover()
        .item-result
          position absolute
          left 0
          right 0
          top 0
          height 100%
          background rgba(73, 94, 130, 0.61)
          display flex
          flex-direction column
          align-items center
          justify-content center
          opacity 0
          &.show
            opacity 1
          .result-percent
            font-size 18px
            font-weight 700
            text-align center
            color #fff
            margin-bottom 10px
          .result-count
            font-size 14px
            color #fff
            text-align center
          .result-slider
            margin 15px 10px 0
            width 70px
            height 2px
            background rgba(255,255,255,0.5)
            border-radius 1px
            .slider-line
              height 100%
              background #fff
              transition all linear 0.3s
              max-width 0%
      .item-img-preview
        position absolute
        right 5px
        top 5px
        z-index 10
        width 22px
        height 22px
        cursor pointer
        background-position -81px -22px
      .item-desc
        position absolute
        left 6px
        top 6px
        z-index 10
        width 19px
        height 19px
        line-height 11px
        border-radius 50%
        background rgba(0,0,0,0.15)
        text-align center
        color #fff
        font-weight 700
      .item-content
        display flex
        align-items center
        padding 10px
        .option-circle
          flex none
          width 14px
          height 14px
          border 1px solid #dde5ed
          border-radius 50%
          margin-right 10px
        .option-square
          flex none
          width 14px
          height 14px
          border 1px solid #dde5ed
          margin-right 10px
        .option-content
          flex 1
          width 0
          line-height 1.4
          font-size 14px
          >>> img, >>> iframe, >>> video
            max-width 100%
  .pic-preview-wrapper
    position fixed
    top 0
    bottom 0
    left 0
    right 0
    z-index 100
    background rgba(0,0,0,0.8)
    .preview-close
      position: absolute;
      right: 10px;
      top: 10px;
      padding: 6px;
      text-align center
      font-size: 14px;
      border-radius: 50%
      color rgba(255,255,255,0.7)
      cursor pointer
    .preview-pagination
      position absolute
      left 0
      right 0
      bottom 0
      height 40px
      line-height 40px
      background rgba(0,0,0,0.7)
      color #fff
      text-align center
      no-wrap()
      font-size 14px
    >>> .swiper-container
      position absolute
      top 50%
      left 0
      right 0
      transform translateY(-50%)
      .pic-item
        width 100%
        padding-bottom 100%
        bgCover()
  .pic-desc-wrapper
    position fixed
    top 0
    bottom 0
    left 0
    right 0
    z-index 1000
    background rgba(0,0,0,0.8)
    .desc-content
      position absolute
      left 0
      right 0
      bottom 0
      height 60%
      background #fff
      display flex
      flex-direction column
      .desc-header
        flex none
        height 36px
        display flex
        align-items center
        justify-content flex-end
        padding-right 16px
        .desc-close
          cursor pointer
      .desc-body
        flex 1
        scroll()
        width auto
        height 0
        padding 0 16px
        .desc-title
          text-align center
          margin-bottom 10px
          line-height 1.4
        .desc-box
          line-height 1.4
          >>> img, >>> iframe, >>> video
            max-width 100% !important
</style>
